import java.io.*;
import java.net.*;
import java.util.*;

public class DataServer {
	
	public Hashtable<Socket, String> usernames = new Hashtable<Socket, String>();
	public Hashtable<Socket, Room>       rooms = new Hashtable<Socket, Room>();
	public Hashtable<String, Room>   roomnames = new Hashtable<String, Room>();
	public Room lobby = new Room("Lobby", Long.MAX_VALUE, this);
	
	static public void main( String args[] ) throws Exception {	
		// Create a Server object, which will automatically begin
		// accepting connections.
		new DataServer( 25432 );
	}
	
	public DataServer( int port ) throws IOException {
		ServerSocket server = new ServerSocket( port );
		System.out.println( "Data Server Listening on " + port);
	
		//Listening Loop that accepts new connections
		while (true) {
			Socket newConnection = server.accept();
			System.out.println(getTimeStamp() + "Opening connection from " + newConnection.getRemoteSocketAddress() );
				
			new DataServerThread( this, newConnection );
		}
	}
	
	public void sendToRoom( String message, String room ) {
		ArrayList<Socket> users = roomnames.get( room ).users;
		synchronized( users ) {
			// For each client ...
			for (int i=0;  i<users.size(); i++) {
				sendToSocket(message, users.get(i));
			}
		}
	}
	
	public void sendToSocket( String message, Socket socket ) {
		try {
			// ... get the output stream ...
			DataOutputStream dout = new DataOutputStream( socket.getOutputStream() );
			// ... and send the message
			dout.writeUTF( message );
			dout.flush();
			//System.out.println( getTimeStamp() + ">> " + message);
		} 
		catch( IOException ie ) { System.out.println( ie ); }
	}
	
	public String getTimeStamp() {
		String timestamp = "[";
		timestamp += Calendar.getInstance().get(Calendar.MONTH) + "/";
		timestamp += Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + " ";
		if(Calendar.getInstance().get(Calendar.HOUR) == 0) {
			timestamp += "12:";
		} else {
			timestamp += Calendar.getInstance().get(Calendar.HOUR) + ":";
		}	
		if (Calendar.getInstance().get(Calendar.MINUTE) > 9) {
			timestamp += Calendar.getInstance().get(Calendar.MINUTE);
		} else {
			timestamp += "0" + Calendar.getInstance().get(Calendar.MINUTE);
		}
		if (Calendar.getInstance().get(Calendar.AM_PM) == Calendar.AM) {
			timestamp += "am] ";
		} else {
			timestamp += "pm] ";
		}
		return timestamp;
	}
	
	public void removeConnection( Socket socket ) {
		// Make sure it's closed
		try {
			System.out.println(this.getTimeStamp() +  "Closing connection from " + socket.getRemoteSocketAddress() );
			Room current_room = rooms.get(socket);
			if (current_room != null)
				current_room.delUser(socket);
			usernames.remove(socket);
			socket.close();
		} 
		catch( IOException ie ) {
			System.out.println( "Error closing " + socket );
			ie.printStackTrace();
		}
	}
}
